package com.yjt.fresh.fragment;
/*
 * 溯源
 */

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter;
import com.donkingliang.groupedadapter.holder.BaseViewHolder;
import com.donkingliang.groupedadapter.layoutmanger.GroupedGridLayoutManager;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.R;
import com.yjt.fresh.activity.AtyHistoryCompanies;
import com.yjt.fresh.activity.AtyHistoryDetail;
import com.yjt.fresh.activity.AtyHistoryVideoList;
import com.yjt.fresh.activity.AtyHistoryVideos;
import com.yjt.fresh.activity.AtyQRScan;
import com.yjt.fresh.adpater.AdpFrgHistoryHome;
import com.yjt.fresh.api.ApiGetHistoryHome;
import com.yjt.fresh.api.ApiGetHistoryHomeData;
import com.yjt.fresh.base.BaseSimpleFragment;
import com.yjt.fresh.bean.BeanHistory;
import com.yjt.fresh.bean.BeanHistoryHome;
import com.yjt.fresh.constant.MyConstants;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.bgabanner.BGABanner;


public class FrgHistory extends BaseSimpleFragment {

    private static final int REQUEST_CODE = 1006;
    private final int CAMERA_REQUEST_CODE = 1;
    @BindView(R.id.ivAppFrgHistorySearch)
    ImageView mIvSearch;
    @BindView(R.id.ivAppFrgHistoryQR)
    ImageView mIvQR;
    @BindView(R.id.bannerAppFrgHistory)
    BGABanner mBanner;
    @BindView(R.id.rvAppFrgHistory)
    RecyclerView mRv;
    private List<BeanHistoryHome.BannerBean> mBeanList;
    private List<BeanHistoryHome.VideoListBean> mVideoList;


    @Override
    protected int getContentView() {
        return R.layout.app_atymain_frg_history;
    }

    @Override
    protected void initView(Bundle savedInstanceState, View view) {
        ButterKnife.bind(this, view);
    }


    @Override
    protected void initEvents() {
        initClick();
        getData();
        getAllData();
    }

    private void getAllData() {
        ApiGetHistoryHomeData apiGetHistoryHomeData = new ApiGetHistoryHomeData(new HttpOnNextListener<BeanHistoryHome>() {
            @Override
            public void onNext(BeanHistoryHome beanHistoryHome) {
                initBanner(beanHistoryHome.getBanner());
                initRv(beanHistoryHome.getVideoList());
            }

            @Override
            public void onReLogin() {

            }
        }, mContext, true, false, false);
        HttpManager.getInstance().doHttpDeal(apiGetHistoryHomeData);
    }

    private void initBanner(List<BeanHistoryHome.BannerBean> banner) {
        mBeanList = banner;
        List<String> imageList = new ArrayList<>();
        for (int i = 0; i < banner.size(); i++) {
            imageList.add(banner.get(i).getCOVERIMAGE());
        }
        mBanner.setAdapter(new BGABanner.Adapter<ImageView, String>() {
            @Override
            public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
                Glide.with(mContext)
                        .load(model)
                        .placeholder(R.mipmap.image_default)
                        .error(R.mipmap.image_default)
                        .dontAnimate()
                        .into(itemView);
            }
        });
        mBanner.setData(imageList, null);
        mBanner.setDelegate(new BGABanner.Delegate() {
            @Override
            public void onBannerItemClick(BGABanner banner, View itemView, @Nullable Object model, int position) {
                Intent intent = new Intent(mContext, AtyHistoryVideos.class);
                intent.putExtra(MyConstants.IS_WEB_VIEW, true);
                intent.putExtra(MyConstants.VIDEO_ID, mBeanList.get(position).getVIDEO_ID());
                intent.putExtra(MyConstants.USER_ID, mBeanList.get(position).getUSER_ID());
                intent.putExtra(MyConstants.CONTENT, mBeanList.get(position).getTITLE());
                intent.putExtra(MyConstants.TITLE, mBeanList.get(position).getTITLE());
                startActivity(intent);
            }
        });
    }

    private void initRv(List<BeanHistoryHome.VideoListBean> videoList) {
        mVideoList = videoList;
        AdpFrgHistoryHome adpFrgHistoryHome = new AdpFrgHistoryHome(mContext, videoList);
        mRv.setAdapter(adpFrgHistoryHome);
        GroupedGridLayoutManager gridLayoutManager = new GroupedGridLayoutManager(mContext, 2, adpFrgHistoryHome);
        mRv.setLayoutManager(gridLayoutManager);
//        mRv.addItemDecoration(new GridSpacingItemDecoration(2, CommonsToolsHelper.dip2px(mContext, 5), false));
        mRv.setHasFixedSize(true);
        mRv.setNestedScrollingEnabled(false);

        adpFrgHistoryHome.setOnHeaderClickListener(new GroupedRecyclerViewAdapter.OnHeaderClickListener() {
            @Override
            public void onHeaderClick(GroupedRecyclerViewAdapter adapter, BaseViewHolder holder, int groupPosition) {
                Intent intent = new Intent(mContext, AtyHistoryVideoList.class);
                intent.putExtra(MyConstants.TITLE, mVideoList.get(groupPosition).getVIDEOTYPE());
                intent.putExtra(MyConstants.VIDEO_TYPE_ID, mVideoList.get(groupPosition).getVIDEOTYPE_ID());
                startActivity(intent);
            }
        });

        adpFrgHistoryHome.setOnChildClickListener(new GroupedRecyclerViewAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(GroupedRecyclerViewAdapter adapter, BaseViewHolder holder, int groupPosition, int childPosition) {
                Intent intent = new Intent(mContext, AtyHistoryVideos.class);
                BeanHistoryHome.VideoListBean.ListBean videoBean = mVideoList.get(groupPosition).getList().get(childPosition);
                intent.putExtra(MyConstants.VIDEO_ID, videoBean.getVIDEO_ID());
                intent.putExtra(MyConstants.USER_ID, videoBean.getSTORE_ID());
                intent.putExtra(MyConstants.CONTENT, videoBean.getTITLE());
                intent.putExtra(MyConstants.TITLE, videoBean.getTITLE());
                startActivity(intent);
            }
        });
    }


    private BeanHistory mBeanHistory;
    HttpOnNextListener<BeanHistory> mHomeListener = new HttpOnNextListener<BeanHistory>() {
        @Override
        public void onNext(BeanHistory beanHistory) {
            mBeanHistory = beanHistory;
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void getData() {
        ApiGetHistoryHome apiGetHistoryHome = new ApiGetHistoryHome(mHomeListener, mContext, true, false, false);
        HttpManager.getInstance().doHttpDeal(apiGetHistoryHome);
    }

    private void initClick() {
        mIvQR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    // 第一次请求权限时，用户如果拒绝，下一次请求shouldShowRequestPermissionRationale()返回true
                    ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST_CODE);

                } else {
                    Intent intent = new Intent(mContext, AtyQRScan.class);
                    startActivityForResult(intent, REQUEST_CODE);
                }
            }
        });

        mIvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, AtyHistoryCompanies.class);
                startActivity(intent);
            }
        });

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(mContext, CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
            } else {
                Toast.makeText(mContext, "相机权限已被禁止", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    if (result.contains(":")) {
                        Intent intent = new Intent(mContext, AtyHistoryDetail.class);
                        intent.putExtra(MyConstants.SOURCE_SID, result.split(":")[1]);
                        intent.putExtra(MyConstants.VIDEO_OBJ, mBeanHistory);
                        startActivity(intent);
                    } else {
                        Toast.makeText(mContext, "解析二维码失败", Toast.LENGTH_LONG).show();
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(mContext, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}
